﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Services.Client;
using TelerikStore.EbayService;
using Telerik.Web.UI;
using TelerikStore.Views;
using TelerikStore.MasterPages;

namespace TelerikStore
{
    public partial class CategoryView1 : System.Web.UI.Page
    {
        private const int AllProducts = 0;

        private RadListView listView;
        private RadGrid grid;
        private RadMenu categoryMenu;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ClearProductsFromSession();

                ProductListView.ListedCategoryId = !String.IsNullOrEmpty(Request.QueryString["Category"]) ? Request.QueryString["Category"].ToString() : String.Empty;
                ProductListView.SearchText = SearchBox.Text = !String.IsNullOrEmpty(Request.QueryString["Search"]) ? Request.QueryString["Search"].ToString() : String.Empty;
                ProductListView.FilterQueryString = GenerateFilterQuery();
            }

            string script = "(function() { $telerik.$('li',$telerik.$('nav')).removeClass('current');  $telerik.$('#products',$telerik.$('nav')).parent().addClass('current'); }());";
            ScriptManager.RegisterStartupScript(Page, GetType(), "SetPane", script, true);

            listView = ProductListView.FindControl("ProductListView") as RadListView;
            grid = ProductGridView.FindControl("ProductGrid") as RadGrid;
            categoryMenu = Page.Master.Master.FindControl("FullContent").FindControl("QuickCategoryMenu") as RadMenu;

            ConfigureAjaxSettings();
        }

        protected void SwitchView_Click(object sender, EventArgs e)
        {
            ProductListView.Visible = !ProductListView.Visible;
            ProductGridView.Visible = !ProductGridView.Visible;

            InitializeControlParameters();
        }

        protected void ApplyFilterButton_Click(object sender, EventArgs e)
        {
            InitializeControlParameters();
        }

        protected void SearchPerformed(object sender, EventArgs e)
        {
            InitializeControlParameters();
        }

        public void InitializeControlParameters()
        {
            string listedCategoryId = categoryMenu.SelectedItem != null ? categoryMenu.SelectedValue : String.Empty;
            InitializeControlParameters(listedCategoryId, SearchBox.Text);
        }

        private void InitializeControlParameters(string ListedCategoryId, string SearchText)
        {
            ClearProductsFromSession();

            ProductGridView.ListedCategoryId = ProductListView.ListedCategoryId = ListedCategoryId;
            ProductGridView.SearchText = ProductListView.SearchText = SearchText;
            ProductGridView.FilterQueryString = ProductListView.FilterQueryString = GenerateFilterQuery();

            if (ProductListView.Visible)
            {
                listView.CurrentPageIndex = 0;
                listView.Rebind();
            }
            else
            {
                grid.Rebind();
            }
        }

        private void ClearProductsFromSession()
        {
            Session.Remove("Products");
        }

        private string GenerateFilterQuery()
        {
            string result = string.Empty;

            //filterbox elements' values
            string condition = ConditionComboBox.SelectedValue;
            string minPrice = StartRange.Text;
            string maxPrice = EndRange.Text;

            result += String.Format("CurrentPrice{0}{3}{2}CurrentPrice{1}{4}", EbayQueryStringsHelper.GreaterThan, EbayQueryStringsHelper.LessThan, EbayQueryStringsHelper.And, minPrice, maxPrice);

            if (!condition.Equals("0"))
                result += String.Format("{0}Condition/Id{1}{2}", EbayQueryStringsHelper.And, EbayQueryStringsHelper.Equal, condition);

            return result;
        }

        private void ConfigureAjaxSettings()
        {
            Home myMasterPage = (Home)this.Master.Master;
            RadAjaxManager manager = RadAjaxManager.GetCurrent(Page);
            Label itemsTotalLabel = (Label)myMasterPage.FindControl("ItemsTotalLabel");
            Label priceTotalLabel = (Label)myMasterPage.FindControl("PriceTotalLabel");

            manager.ClientEvents.OnRequestStart = "ajaxManagerRequestStart";
            manager.AjaxRequest += new RadAjaxControl.AjaxRequestDelegate(RadAjaxManager1_AjaxRequest);

            manager.AjaxSettings.AddAjaxSetting(DisplayPlaceHolder, itemsTotalLabel);
            manager.AjaxSettings.AddAjaxSetting(DisplayPlaceHolder, priceTotalLabel);
            manager.AjaxSettings.AddAjaxSetting(manager, DisplayPlaceHolder, LoadingPanel);
            manager.AjaxSettings.AddAjaxSetting(manager, StartRange);
            manager.AjaxSettings.AddAjaxSetting(manager, EndRange);
            manager.AjaxSettings.AddAjaxSetting(manager, PriceSlider);
            manager.AjaxSettings.AddAjaxSetting(manager, ConditionComboBox);
            manager.AjaxSettings.AddAjaxSetting(manager, SearchBox);
        }

        protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            String[] arguments = e.Argument.Split(",".ToCharArray());

            if (arguments.Length != 0 && arguments[0] == "Category")
            {
                StartRange.Value = (int)Price.Min;
                EndRange.Value = (int)Price.Max;
                PriceSlider.SelectionStart = PriceSlider.MinimumValue;
                PriceSlider.SelectionEnd = PriceSlider.MaximumValue;
                ConditionComboBox.SelectedIndex = 0;
                SearchBox.Text = String.Empty;

                InitializeControlParameters(arguments[1], SearchBox.Text);
            }
        }
    }
}
